package com.huawei.bus.minitest.db;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;
import org.apache.commons.dbcp.datasources.SharedPoolDataSource;

import com.huawei.bus.minitest.conf.Conf;
import com.huawei.bus.minitest.conf.DatabaseConf;

public class DatasourcePool {
	
	private static DataSource sysds;
	private static DataSource[] userds;
	private static DataSource[] cbpds;
	
	public static Connection getSysdbConnection() throws SQLException{
		return (sysds != null) ? sysds.getConnection() : null;
	}
	
	public static Connection getUserdbConnection(int i) throws SQLException{
		if(userds != null){
			if(userds.length >= i+1){
				return userds[i].getConnection();
			}
		}
		return null;
	}
	
	public static Connection getCbpdbConnection(int i) throws SQLException{
		if(cbpds != null){
			if(cbpds.length >= i+1){
				return cbpds[i].getConnection();
			}
		}
		return null;
	}
	
	static {
		if(Conf.sysdb != null){
			sysds = createPooledDatasource(getDriver(Conf.sysdb.getDbtype()), Conf.sysdb.getUrl(), Conf.sysdb.getUsername(), decript(Conf.sysdb.getPassword()));
		}
		if(Conf.userdbs != null && Conf.userdbs.length>0){
			userds = new SharedPoolDataSource[Conf.cbpdbs.length];
			for (int i = 0; i < Conf.userdbs.length; i++) {
				DatabaseConf userdb = Conf.userdbs[i];
				userds[i] = createPooledDatasource(getDriver(userdb.getDbtype()), userdb.getUrl(), userdb.getUsername(), decript(userdb.getPassword()));
			}
		}
		if(Conf.cbpdbs != null && Conf.cbpdbs.length>0){
			cbpds = new SharedPoolDataSource[Conf.cbpdbs.length];
			for (int i = 0; i < Conf.cbpdbs.length; i++) {
				DatabaseConf cbpdb = Conf.cbpdbs[i];
				cbpds[i] = createPooledDatasource(getDriver(cbpdb.getDbtype()), cbpdb.getUrl(), cbpdb.getUsername(), decript(cbpdb.getPassword()));
			}
		}
	}

	private static DataSource createPooledDatasource(String driver, String url, String user, String password) {
		DriverAdapterCPDS cpds = new DriverAdapterCPDS();
        try {
			cpds.setDriver(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
        cpds.setUrl(url);
        cpds.setUser(user);
        cpds.setPassword(password);

        SharedPoolDataSource tds = new SharedPoolDataSource();
        tds.setConnectionPoolDataSource(cpds);
        tds.setMaxActive(10);
        tds.setMaxWait(20);

        return tds;
	}

	private static String getDriver(String dbtype) {
		if("oracle".equalsIgnoreCase(dbtype)){
			//TODO yichengfeng
		}
		else if("informix".equalsIgnoreCase(dbtype)){
			//TODO yichengfeng
		}
		else if("mysql".equalsIgnoreCase(dbtype)){
			return "com.mysql.jdbc.Driver";
		}
		return null;
	}

	private static String decript(String password) {
		// TODO yichengfeng
		return password;
	}
}
